package com.dgut.sales.controller;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.dgut.sales.bean.Salesman;
import com.dgut.sales.dynamic.sql.bean.SalesmanSearch;
import com.dgut.sales.service.SalesmanService;

@Controller
@RequestMapping("/salesman")
public class SalesManController {
	
	@Autowired
	private SalesmanService service;
	
	@GetMapping("/list")
	public String list(Model model) {
		List<Salesman> salesmans = service.getAllSalesman();
		model.addAttribute("salesmans", salesmans);
		return "salesman/salesmanList";
	}
	
	@PostMapping("/inputSalesman")
	public String inputSalesman(Model model) {
		model.addAttribute("salesman", new Salesman());
		return "/salesman/inputSalesman";
	}
	
	@PostMapping("/addSalesman")
	public String addSalesman(@ModelAttribute Salesman salesman) {
		service.addSalesman(salesman);
		return "redirect:/salesman/list";
	}
	
	@GetMapping("/deleteSalesman/{id}")
	public String deleteSalesman(@PathVariable("id") Integer id) {
		service.deleteSalesman(id);
		return "redirect:/salesman/list";
	}
	
	@GetMapping("/edit/{id}")
	public String edit(@PathVariable("id") Integer id, Model model) {
		Salesman salesman = service.getSalesById(id);
		model.addAttribute("salesman", salesman);
		return"salesman/editSalesman";
	}
	
	@PutMapping("/update")
	public String update(@ModelAttribute Salesman salesman) {
		service.update(salesman);
		return "redirect:/salesman/list";
	}
	
	@PostMapping("/inputCondition")
	public String inputCondition(Model model) {
		model.addAttribute("searchSalesman", new SalesmanSearch());
		return "salesman/inputCondition";
	}
	
	
	@PostMapping("/search")
	public String search(@ModelAttribute SalesmanSearch salesmanSearch, Model model) {
		List<Salesman> salesmans = service.search(salesmanSearch);
		model.addAttribute("salesmans", salesmans);
		return "salesman/searchResult";
	}

	@GetMapping("/statistics")
	public String statistics(Model model) {
		List<Map<String, Object>> fromSalesmanStatistics = service.searchSalesmanWithMoney();
		model.addAttribute("fromSalesmanStatistics", fromSalesmanStatistics);
		return "statistics/fromSalesman";
	}
}
